package com.vincent.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author vincent
 * @date 2019/10/14
 * @description
 */
@Slf4j
public class ResourceUtils {
    /**
     * 获取resource目录下的资源文件内容
     *
     * @param path 路径以必须以/开始，及根目录
     * @return
     */
    public static String readResource(String path) {
        StringBuilder builder = new StringBuilder();
        ClassPathResource classPathResource = new ClassPathResource(path);
        // 使用try resource catch写法，更加简洁，不需要在finally中判空关闭。
        try (InputStream inputStream = classPathResource.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            log.error("资源文件获取失败, path={}", path, e);
        }
        return builder.toString();
    }
}
